package com.duoqin.syncassistant;

import android.app.Application;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.widget.Toast;

import com.duoqin.account.data.LoginResponse;
import com.duoqin.account.DuoqinAccount;
import com.duoqin.syncassistant.data.BackupFileInfo;
import com.duoqin.syncassistant.data.UserInfo;

public class SyncAssistantApplication extends Application {

    private static final String TAG = "duoqin";

    public static final String INTENT_ACTION_TOKEN_EXPIRED = "token_expired";

    public static final int MAX_BACKUP_FILE_ALLOWED = 5;

    private static SyncAssistantApplication sInstance;

    private SharedPreferences mSharedPreference;

    public BackupFileInfo mVCardInfo = new BackupFileInfo(); // latest vCard info
    public BackupFileInfo mSMSInfo = new BackupFileInfo(); // latest SMS info
    public SparseArray<BackupFileInfo> mAllVCards = new SparseArray<>(); // all server stored vCard info
    public SparseArray<BackupFileInfo> mAllSMSFiles = new SparseArray<>(); // all server stored SMS info

    @Override
    public void onCreate() {
        super.onCreate();
        sInstance = this;
        mSharedPreference = PreferenceManager.getDefaultSharedPreferences(this);

        migrateAccount();
    }

    public static SyncAssistantApplication getsInstance() {
        return sInstance;
    }

    public SharedPreferences getSharedPreference() {
        return mSharedPreference;
    }

    private void migrateAccount() {
        String accountName = mSharedPreference.getString(UserInfo.PREFERENCE_KEY_MOBILE, null);
        if (TextUtils.isEmpty(accountName)) return;

        LoginResponse.DataBean dataBean = new LoginResponse.DataBean();
        dataBean.setUid(mSharedPreference.getString(UserInfo.PREFERENCE_KEY_UID, null));

        String token = mSharedPreference.getString(UserInfo.PREFERENCE_KEY_TOKEN, null);
        long expiredAt = mSharedPreference.getLong(UserInfo.PREFERENCE_KEY_EXPIREDAT, -1);
        if (expiredAt > System.currentTimeMillis()) {
            dataBean.setAccessToken(token);
            dataBean.setExpiredAt(expiredAt);
        } else {
            dataBean.setAccessToken(null);
            dataBean.setExpiredAt(-1);
        }

        DuoqinAccount.addAccount(getApplicationContext(), accountName, null, dataBean);
        Log.i(TAG, "migrateAccount success");

        mSharedPreference.edit().remove(UserInfo.PREFERENCE_KEY_MOBILE).apply();
        mSharedPreference.edit().remove(UserInfo.PREFERENCE_KEY_UID).apply();
        mSharedPreference.edit().remove(UserInfo.PREFERENCE_KEY_TOKEN).apply();
        mSharedPreference.edit().remove(UserInfo.PREFERENCE_KEY_EXPIREDAT).apply();
    }

    public void clearUserInfo() {
        DuoqinAccount.removeAllAccounts(this);
        clearToken();
    }

    public void updateToken(String token, long expiredAt) {
        DuoqinAccount.updateAccountToken(this, token, expiredAt);
    }

    public void clearToken() {
        updateToken(null, -1);
        mVCardInfo = new BackupFileInfo();
        mAllVCards.clear();
        mSMSInfo = new BackupFileInfo();
        mAllSMSFiles.clear();
        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(INTENT_ACTION_TOKEN_EXPIRED));
    }

    public boolean hasLogin() {
        int loginState = DuoqinAccount.getLoginState(this);
        if (DuoqinAccount.LOGIN_STATE_SUCCESS == loginState) {
            return true;
        } else if (DuoqinAccount.LOGIN_STATE_TOKEN_EXPIRED == loginState) {
            Toast.makeText(getApplicationContext(), R.string.error_login_token_expired,
                    Toast.LENGTH_SHORT).show();
            clearToken();
            return false;
        }
        return false;
    }
}
